package com.qf.air.service.impl;

import com.qf.air.enums.AirEnum;
import com.qf.air.exception.AirEx;
import com.qf.air.service.SearchService;
import com.qf.air.util.R;
import com.qf.air.vo.ResultVO;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResultVO findByPageAndDistrictId(Map map) throws IOException {
        //1. 创建SearchRequest
        SearchRequest searchRequest = new SearchRequest();

        //2. 封装数据
        //2.1 索引名称
        searchRequest.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2.2 查询条件(BoolQuery)
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.2.1 districtId区域id
        Integer districtId = (Integer) map.get("districtId");
        if(districtId != null && districtId != 0){
            boolQuery.must(QueryBuilders.termQuery("districtId",districtId));
        }
        //2.2.2 monitoringStation监测站名称
        String monitoringStation = (String) map.get("monitoringStation");
        if(!StringUtils.isEmpty(monitoringStation)){
            boolQuery.must(QueryBuilders.matchQuery("monitoringStation",monitoringStation));
        }

        //2.2.3 startTime开始时间
        String startTime = (String) map.get("startTime");
        if(!StringUtils.isEmpty(startTime)){
            boolQuery.must(QueryBuilders.rangeQuery("monitorTime").gte(startTime));
        }

        //2.2.4 endTime结束时间
        String endTime = (String) map.get("endTime");
        if(!StringUtils.isEmpty(endTime)){
            boolQuery.must(QueryBuilders.rangeQuery("monitorTime").lte(endTime));
        }
        // 2.2.5 封装到sourceBuilder
        sourceBuilder.query(boolQuery);

        //2.3 分页信息
        Integer page = (Integer) map.get("page");
        Integer rows = (Integer) map.get("rows");
        sourceBuilder.from((page - 1) * rows);
        sourceBuilder.size(rows);

        //2.4 高亮查询
        if(!StringUtils.isEmpty(monitoringStation)) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("monitoringStation");
            highlightBuilder.preTags("<span style='color:red;'>");
            highlightBuilder.postTags("</span>");
            highlightBuilder.fragmentSize(99999);
            sourceBuilder.highlighter(highlightBuilder);
        }

        //2.5 封装到request中
        searchRequest.source(sourceBuilder);

        //3. 发送请求,获取Response
        SearchResponse resp = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //4. 通过Response解析数据封装为ResultVO
        ResultVO vo = R.ok();
        //4.1 封装数据的总条数
        vo.setCount(resp.getHits().getTotalHits().value);

        //4.2 封装具体的数据
        List<Map> data = new ArrayList<>();
        SearchHit[] hits = resp.getHits().getHits();
        for (SearchHit hit : hits) {
            Map<String, Object> source = hit.getSourceAsMap();
            data.add(source);
        }
        if(!StringUtils.isEmpty(monitoringStation)){
            // 说明有高亮显示
            for (int i = 0; i < hits.length; i++) {
                HighlightField monitoringStationHighlight = hits[i].getHighlightFields().get("monitoringStation");
                String highLight = monitoringStationHighlight.fragments()[0].toString();
                data.get(i).put("monitoringStation",highLight);
            }
        }
        vo.setData(data);
        //5. 返回
        return vo;
    }

    @Override
    public void add(Map map) throws IOException {
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("air");
        indexRequest.id(map.get("id") + "");
        indexRequest.source(map);
        IndexResponse resp = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        if(!resp.getResult().toString().equalsIgnoreCase("CREATED")){
            System.out.println("添加信息失败！ air=" + map);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }
    }


    @Override
    public ResultVO findDistrictAirQualityCount() throws IOException {
        //1. SearchRequest
        SearchRequest request = new SearchRequest();

        //2. set Data,封装Request
        request.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.terms("airCount").field("districtName").size(5));
        request.source(sourceBuilder);
        //3. send Request,获取Response
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //4. 封装数据
        ResultVO vo = R.ok();
        Terms provinceCount = resp.getAggregations().get("airCount");
        List<Map> data = new ArrayList<>();
        for (Terms.Bucket bucket : provinceCount.getBuckets()) {
            Map map = new HashMap();
            map.put("key",bucket.getKey() + "");
            map.put("docCount",bucket.getDocCount());
            data.add(map);
        }
        vo.setData(data);
        return vo;
    }






    /*
    {"id":62,"districtId":1,"monitorTime":"2021-11-01","pm10":12,"pm25":12,"monitoringStation":"12","lastModifyTime":"2021-11-09 15:08:55","districtName":"西城"}
     */




}
